# socket_events.py
from .app import socketio, db
from .models import Feedback, User
from flask_login import current_user
from flask import request

@socketio.on('connect')
def handle_connect():
    if current_user.is_authenticated:
        socketio.server.enter_room(request.sid, f'user_{current_user.id}')
        print(f"用户 {current_user.id} 已连接, 房间: user_{current_user.id}")

@socketio.on('disconnect')
def handle_disconnect():
    if current_user.is_authenticated:
        socketio.server.leave_room(request.sid, f'user_{current_user.id}')
        print(f"用户 {current_user.id} 已断开连接")

@socketio.on('feedback_processed')
def handle_feedback_processed(data):
    feedback_id = data['feedback_id']
    response_id = data['response_id']
    
    # 通知所有管理员
    socketio.emit('feedback_processed_admin', {
        'feedback_id': feedback_id,
        'response_id': response_id
    }, broadcast=True)
    
    # 通知反馈提交者
    feedback = Feedback.query.get(feedback_id)
    if feedback:
        socketio.emit('feedback_processed', {
            'feedback_id': feedback_id,
            'response_id': response_id
        }, room=f'user_{feedback.user_id}')
        print(f"已通知用户 {feedback.user_id} 反馈 {feedback_id} 有新的回复")